/*
 * @(#)TaskService.java
 * 2013-2-25 下午02:59:18
 * 
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.task.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.qyxx.platform.common.orm.Page;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.inf.gps.service.BaiDuMapService;
import com.qyxx.platform.sysmng.accountmng.dao.UserDao;
import com.qyxx.platform.sysmng.notice.entity.Notice;
import com.qyxx.platform.sysmng.notice.service.NoticeManager;
import com.qyxx.platform.sysmng.task.dao.TaskDao;
import com.qyxx.platform.sysmng.task.entity.Task;
import com.qyxx.platform.sysmng.task.entity.TaskContentJson;


/**
 *  任务Service
 *  @author gxj
 *  @version 1.0 2013-2-25 下午02:59:18
 *  @since jdk1.6 
 */
@Service
@Transactional
public class TaskManager {
	
	private static Logger logger = LoggerFactory.getLogger(TaskManager.class);
	
	private static final String ID = "id";

	private TaskDao taskDao;
	
	private NoticeManager noticeManager;
	
	private UserDao userDao;
	
	/**
	 * @param userDao
	 */
	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	/**
	 * @return taskDao
	 */
	public TaskDao getTaskDao() {
		return taskDao;
	}

	
	/**
	 * @param taskDao
	 */
	@Autowired
	public void setTaskDao(TaskDao taskDao) {
		this.taskDao = taskDao;
	}

	
	/**
	 * @return noticeManager
	 */
	public NoticeManager getNoticeManager() {
		return noticeManager;
	}


	
	/**
	 * @param noticeManager
	 */
	@Autowired
	public void setNoticeManager(NoticeManager noticeManager) {
		this.noticeManager = noticeManager;
	}


	/**
	 * 分页查询任务
	 * 
	 * @param page
	 * @param filters
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<Task> searchTask(final Page<Task> page, final List<PropertyFilter> filters) {
		return preHandlePage(taskDao.findPage(page, filters));
	}
	
	/**
	 * 条件查询任务
	 * 
	 * @param filters
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Task> findTaskList(final List<PropertyFilter> filters) {
		return taskDao.find(filters);
	}

	/**
	 * 查询任务
	 * 
	 * @param id
	 * @return
	 */
	@Transactional(readOnly = true)
	public Task getTask(Long id) {
		return taskDao.get(id);
	}
	
	/**
	 * 查询任务，session无关
	 * 
	 * @param id
	 * @return
	 */
	@Transactional(readOnly = true)
	public Task getTaskWithoutSession(Long id) {
		Task entity = taskDao.get(id);
		taskDao.initProxyObject(entity);
		taskDao.evict(entity);
		return entity;
	}
	
	/**
	 * 保存任务
	 * 
	 * @param entity
	 * @param userId
	 */
	public void saveTask(Task entity, Long userId) {
		if(null!=entity.getId()) {
			entity.setLastUpdateUser(userId);
			entity.setLastUpdateTime(new Date());
		} else {
			entity.setCreateUser(userId);
			entity.setCreateTime(new Date());
		}
		taskDao.save(entity);
	}
	
	/**
	 * 批量删除任务
	 * 
	 * @param ids
	 */
	public void deleteTask(Long[] ids) {
		if(null != ids) {
			for(Long id : ids) {
				taskDao.delete(id);
			}
		}
	}
	
	/**
	 * 运行预警通知任务
	 * 
	 * @param tcj
	 */
	public void runNoticeTask(TaskContentJson tcj) {
		List<Map<String, Object>> list = taskDao.findDataMapListBySql(tcj.getQuerySql(), null);
		if(null!=list && !list.isEmpty()) {
			for(Map<String, Object> obj : list) {
				String content = tcj.getNoticeVal();
				for(Map.Entry<String, Object> en : obj.entrySet()) {
					String key = en.getKey();
					String val = String.valueOf(en.getValue());
					if(null!=key) {
						content = content.replaceAll("\\$\\{" + key + "\\}", val);
					}
				}
				String title = content;
				String destType = tcj.getDestType();
				Object o = obj.get(ID);
				String id = "";
				if(o == null) {
					id = String.valueOf(obj.get("ID"));
				} else {
					id = String.valueOf(o);
				}
				if(TaskContentJson.DEST_TYPE_OWNER.equalsIgnoreCase(destType)) {
					//所有者
					String userIdKey = tcj.getDestVal();
					Long userId = NumberUtils.toLong(String.valueOf(obj.get(userIdKey)));
					List<Long> userIdList = new ArrayList<Long>();
					userIdList.add(userId);
					noticeManager.sendNotice(title, Notice.STYLE_02, id, tcj.getModuleKey(), null, userIdList);
				} else if(TaskContentJson.DEST_TYPE_ROLE.equalsIgnoreCase(destType)) {
					//角色
					noticeManager.sendNotice(title, Notice.STYLE_02, id, tcj.getModuleKey(), null, tcj.getDestVal());
				}
				
			}
		}
	}
	
	/**
	 * 运行GPS更新任务
	 * 
	 * @param tcj
	 */
	public void runGpsUpdateTask(TaskContentJson tcj) {
		List<Map<String, Object>> list = taskDao.findDataMapListBySql(tcj.getQuerySql(), null);
		String coordtype = tcj.getExecuteType();
		if(null!=list && !list.isEmpty()) {
			for(Map<String, Object> obj : list) {
				String id = String.valueOf(obj.get("id"));
				String address = String.valueOf(obj.get("address"));
				try {
					Map<String, String> result = BaiDuMapService.getGpsByAddressResult(address, coordtype);
					String lat = result.get("lat");
					String lng = result.get("lng");
					List<PropertyFilter> pfList = Lists.newArrayList();
					pfList.add(new PropertyFilter("EQL_id", id));
					pfList.add(new PropertyFilter("EQS_lat", lat));
					pfList.add(new PropertyFilter("EQS_lng", lng));
					taskDao.execSql(tcj.getUpdateSql(), pfList);
				} catch(Exception e) {
					logger.error("执行ID为" + id + "的GPS地址(" + address + ")更新出现异常：", e);
				}
			}
		}
	}
	
	/**
	 * 处理Page对象，翻译字段
	 * 
	 * @param page
	 * @return
	 */
	public Page<Task> preHandlePage(Page<Task> page) {
		List<Task> list = page.getResult();
		if(list != null) {
			for(Task n : list) {
				n.setCreateUserCaption(userDao.getUserNameById(n.getCreateUser()));
			}
		}
		return page;
	}
	
	
}
